package com.unione.unione_voice.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;

import com.unione.unione_base.BaseApplication;


public class NetWorkUtil {
    /**
     * 判断当前网络是否可用(6.0以上版本)
     * 实时
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public static boolean isUsable() {
        boolean isNetUsable = false;
        ConnectivityManager manager = (ConnectivityManager)
                BaseApplication.Companion.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkCapabilities networkCapabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());
            if (networkCapabilities != null) {
                isNetUsable = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
            }
        }
        return isNetUsable;
    }

    @SuppressLint("MissingPermission")
    public static int getConnectedNetworkType(Context context){
        ConnectivityManager manager = (ConnectivityManager)
                BaseApplication.Companion.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities networkCapabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());
        if (networkCapabilities != null) {
            if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)){
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                    return NetworkCapabilities.TRANSPORT_CELLULAR;
                }else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                    return NetworkCapabilities.TRANSPORT_WIFI;
                }else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
                    return NetworkCapabilities.TRANSPORT_ETHERNET;
                }else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_USB)){
                    return NetworkCapabilities.TRANSPORT_USB;
                }else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)){
                    return NetworkCapabilities.TRANSPORT_BLUETOOTH;
                }
            }
        }
        return -1;
    }

}
